import { program } from 'commander';
import inquirer from 'inquirer';
import chalk from 'chalk';
import fsExtra from 'fs-extra';
import { fileURLToPath } from 'url';
import path, { dirname } from 'path';

// 获取当前模块的文件路径
const __filename = fileURLToPath(import.meta.url);

// 获取当前模块所在的目录路径
const __dirname = dirname(__filename);

program
  .command('create')
  .argument('<project-name>', '项目名称')
  .action(async (projectName) => {
    const { template } = await inquirer.prompt([
      {
        type: 'select',
        name: 'template',
        message: '请选择您的项目框架：',
        choices: ['Vue', 'React'],
      },
    ]);

    try {
      const src = path.join(__dirname, 'templates', template);
      const dest = path.join(process.cwd(), projectName);
      if (fsExtra.existsSync(dest)) {
        const { shouldReplace } = await inquirer.prompt([
          {
            type: 'confirm',
            name: 'shouldReplace',
            message: '项目已存在，是否替换？',
          },
        ]);
        if (!shouldReplace) return;
      }
      await fsExtra.copy(src, dest);
      console.log(chalk.green('项目创建成功！'));
    } catch (error) {
      console.log(chalk.red('项目创建失败！'));
    }
  });

program.parse();
